//
//  ReplyTweetViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-12.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "ReplyTweetViewController.h"

#import "TwitterClient.h"


@implementation ReplyTweetViewController

@synthesize tweet;
@synthesize txt;
@synthesize lblNum;
@synthesize cllManager;

@synthesize acType;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	UIBarButtonItem *btnSend = [[UIBarButtonItem alloc] initWithTitle:@"Send" style:UIBarButtonItemStyleDone target:self action:@selector(sendTweet:)];
	self.navigationItem.rightBarButtonItem = btnSend;
	[btnSend release];
}

- (void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	if(tweet){
		if(acType == AC_TYPE_RT){
			txt.text = [NSString stringWithFormat:@"RT @%@: %@",tweet.usr.screen_name,tweet.text];
			txt.editable = NO;
			self.navigationItem.title = @"RT Tweet";
			// [txt becomeFirstResponder];
		}else if(acType == AC_TYPE_REPLY){
			txt.text = [NSString stringWithFormat:@"@%@ ",tweet.usr.screen_name];
			self.navigationItem.title = NSLocalizedString(@"REPLY",@"");
			txt.editable = YES;
			[txt becomeFirstResponder];
		}
	}else {
		self.navigationItem.title = NSLocalizedString(@"WRITE_TWEET",@""); // @"Write Tweet";
		txt.editable = YES;
		[txt becomeFirstResponder];
	}
	self.lblNum.text = [NSString stringWithFormat:@"%d",(140 - [txt.text length])];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	self.tweet = nil;
	self.cllManager = nil;
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.tweet = nil;
	self.txt = nil;
	self.lblNum = nil;
	self.cllManager = nil;
}
	
#pragma mark -
#pragma mark UIBarButtonItem Action

- (IBAction)genLocationURL:(id)sender{
	CLLocationManager *manager = self.cllManager;
	if(manager == nil){
		manager = [[CLLocationManager alloc] init];
		self.cllManager = manager;
		[manager release];
	}
	
	if(manager.locationServicesEnabled != NO){
		manager.delegate = self;
		[manager startUpdatingLocation];
	}	
}

- (IBAction)sendTweet:(id)sender{
	//if(ccv == nil){
//		ccv = [[ComfrimViewController alloc] initWithNibName:@"ComfirmView" bundle:nil];
//	}
	[txt resignFirstResponder];
	//[self presentModalViewController:ccv animated:NO];
	NSMutableDictionary *params = [NSMutableDictionary dictionary];
	switch (acType) {
		case AC_TYPE_WRITE:
			// TODO Send Tweet use statuses/update
			[params setObject:self.txt.text forKey:@"status"];
			break;
		case AC_TYPE_REPLY:
			// TODO Reply Tweet use statuses/update and in_reply_to_status parameter
			[params setObject:self.txt.text forKey:@"status"];
			[params setObject:tweet.tid forKey:@"in_reply_to_status"];
			break;
		case AC_TYPE_RT:
			// TODO RT Tweet use statuses/retweet
			[params setObject:self.tweet.tid forKey:@"tt_id"];
			break;

		default:
			break;
	}
	
	if(acType == AC_TYPE_RT){
		[NSThread detachNewThreadSelector:@selector(sendRT:) toTarget:self withObject:params];
	}else{
		[NSThread detachNewThreadSelector:@selector(sendStatus:) toTarget:self withObject:params];
	}
}

- (void)sendStatus:(NSDictionary *)args{
	TwitterClient *client = [TwitterClient getInstance];
	[client doStatusesUpdate:args];
}

- (void)sendRT:(NSDictionary *)args{
	TwitterClient *client = [TwitterClient getInstance];
	[client doStatusesRetweet:args];
}

#pragma mark -
#pragma mark CLLocationManagerDelegate Implement

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	// TODO 定位失败提示
	// NSLog([error description]);
}

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation{
	
	NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 10.0) return; // 上一次的事件差
    // test that the horizontal accuracy does not indicate an invalid measurement
    if (newLocation.horizontalAccuracy < 0) return;
    // test the measurement to see if it is more accurate than the previous measurement
    	
	// TODO 更新定位
	NSString *oldText = self.txt.text;
	NSString *locURL = [[NSString alloc] initWithFormat:@"http://maps.google.com/maps?q=%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude];
	NSString *str = [TwitterClient shortenURL:locURL];	
	NSString *nt = @"";
	if(str){
		nt = [[NSString alloc] initWithFormat:@"%@ I'm at %@ ",oldText,str];
	}else{
		nt = [[NSString alloc] initWithFormat:@"%@ I'm at %@ ",oldText,locURL];
	}
	[locURL release];
	self.txt.text = nt;
	[nt release];
	
	[manager stopUpdatingLocation];
}

#pragma mark -
#pragma mark UITextViewDelegate Implement

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
	return [textView.text length] >= 140;
}

- (void)textViewDidChange:(UITextView *)textView{
	self.lblNum.text = [NSString stringWithFormat:@"%d",(140 - [textView.text length])];
}

#pragma mark -
- (void)dealloc {
	[tweet release];
	[cllManager release];
	[ccv release];
    [super dealloc];
}


@end
